
# -*- coding: utf-8 -*-
import uuid
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import APIRouter, Depends

from core.database import db_getter
from core.exception import CustomException
from utils.response import SuccessResponse
from application import constant
from . import schemas, models, params
from .crud import JobDal, ScheduleDal, JobLogsDal
from apps.license.models import License
from apps.license.crud import LicenseDal
from apps.statistics.crud import StatisticsDal
from apps.statistics.schemas import StatisticsOut

app = APIRouter()


@app.post("/add", summary="添加任务")
async def add_job(
    data: schemas.AddJobIn,
    db: AsyncSession = Depends(db_getter),
):
    license: License = await LicenseDal(db).get_data(activation_code=data.activation_code, v_return_none=False)
    job_count = await JobDal(db).get_count(activation_code=data.activation_code)
    if job_count >= license.task_num:
        return CustomException(**constant.ErrorsEnum.LICENSE_OUT_TASK_NUM_LIMIT.to_dict())

    d = data.model_dump()
    d['task_id'] = str(uuid.uuid4())
    d['status'] = str(constant.JobStatusEnum.WAITING)
    job = await JobDal(db).create_data(data=d, v_schema=schemas.JobOut)
    return SuccessResponse(job)

@app.get("/list", summary="任务列表")
async def get_job_list(
    params: params.JobParams = Depends(),
    db: AsyncSession = Depends(db_getter),
):
    datas, count = await JobDal(db).get_datas(
        **params.dict(),
        v_schema=schemas.JobOut,
        v_return_count=True,
    )
    return SuccessResponse(datas, count=count)

@app.delete("/delete", summary="删除任务")
async def delete_job(
    data: schemas.DeleteJobIn,
    db: AsyncSession = Depends(db_getter),
):
    dal = JobDal(db)
    job: models.Job = await dal.get_data(task_id=data.task_id, v_return_none=False)
    await dal.delete_data(id=job.id, v_soft=False)


    statistics_dal = StatisticsDal(db)
    statistics = await statistics_dal.get_datas(task_id=job.task_id, v_return_count=False, limit=0, v_schema=StatisticsOut)
    statistics_ids = [i['id'] for i in statistics]
    await statistics_dal.delete_datas(ids=statistics_ids, v_soft=False)

    return SuccessResponse('ok')


@app.put("/status", summary="更新任务状态")
async def update_job_status(
    data: schemas.PutJobStatusIn,
    db: AsyncSession = Depends(db_getter),
):
    dal = JobDal(db)
    job: models.Job = await dal.get_data(task_id=data.task_id, v_return_none=False)
    job_out = await JobDal(db).put_data(data_id=job.id, data={'status': data.status,'remark':data.remark}, v_schema=schemas.JobOut)

    return SuccessResponse(job_out)


@app.post("/schedule/add", summary="添加定时任务")
async def add_schedule_job(
    data: schemas.AddScheduleIn,
    db: AsyncSession = Depends(db_getter),
):
    d = data.model_dump()
    d['schedule_id'] = str(uuid.uuid4())
    return SuccessResponse(await ScheduleDal(db).create_data(data=d, v_schema=schemas.ScheduleOut))


@app.delete("/schedule/delete", summary="删除定时任务")
async def delete_schedule_job(
    data: schemas.DeleteScheduleIn,
    db: AsyncSession = Depends(db_getter),
):
    dal = ScheduleDal(db)
    schecule: models.Schedule = await dal.get_data(schedule_id=data.schedule_id, v_return_none=False)
    await dal.delete_data(id=schecule.id, v_soft=False)
    return SuccessResponse('ok')


@app.get("/schedule/list", summary="定时任务列表")
async def get_schedule_job_list(
    params: params.ScheduleParams = Depends(),
    db: AsyncSession = Depends(db_getter),
):
    datas, count = await ScheduleDal(db).get_datas(
        **params.dict(),
        v_return_objs=True,
        v_return_count=True,
    )
    result = []
    for data in datas:
        d = schemas.ScheduleOut(
            id=data.id,
            name=data.name,
            schedule_id=data.schedule_id,
            execute_time=data.execute_time,
            activation_code=data.activation_code,
            create_datetime=data.create_datetime,
            update_datetime=data.update_datetime,
            task_ids=data.task_ids,
        ).model_dump()
        d['tasks'] = await JobDal(db).get_datas(task_id=('in', data.task_id_list), v_schema=schemas.JobOut, v_return_count=False, limit=0)
        result.append(d)
    return SuccessResponse(result, count=count)

@app.post("/logs/add", summary="添加日志")
async def add_logs(
    data: schemas.AddJobLogsIn,
    db: AsyncSession = Depends(db_getter),
):
    return SuccessResponse(await JobLogsDal(db).create_data(data=data, v_schema=schemas.JobLogsOut))


@app.get("/logs/list", summary="日志列表")
async def get_logs_list(
    params: params.JobLogsParams = Depends(),
    db: AsyncSession = Depends(db_getter),
):
    datas, count = await JobLogsDal(db).get_datas(
        **params.dict(),
        v_return_count=True,
        v_schema=schemas.JobLogsOut,
    )
    return SuccessResponse(datas, count=count)
    